import { AppServiceUtility } from "src/projects/app/appService";
import { beforeUpload } from "src/projects/app/util-tool";
import { addon, Permission } from "pao-aop";
import { reactControl, ReactViewControl, ReactViewState, ReactView } from "pao-aop-client";
import { MainContent } from "src/business/components/style-components/main-content";
import { isPermission } from "src/projects/app/permission";
import React from "react";
import Form from "antd/lib/form/Form";
// import { ROUTE_PATH } from "src/projects/router";
import { remote } from "src/projects/remote";
import { Row, Button, Col, Input, Card, message } from "antd";
import { MainCard } from "src/business/components/style-components/main-card";
import { FileUploadBtn } from "src/business/components/buss-components/file-operation-btn/file-upload-btn";
import TextArea from "antd/lib/input/TextArea";
// import { ROUTE_PATH } from "src/projects/router";
import { request } from "src/business/util_tool";
import { checkMin1, checkMin0 } from './validate';
import { DatePicker } from 'antd';
import moment from "moment";
const { RangePicker } = DatePicker;
/**
 * 状态：活动室新增页面
 */
export interface ChangeActivityRoomViewState extends ReactViewState {
    // 详情
    data_info: any;
    // 设备详情
    data_activity_device_list: any;
}

/**
 * 组件：活动室新增页面视图
 */
export class ChangeActivityRoomView extends ReactView<ChangeActivityRoomViewControl, ChangeActivityRoomViewState> {
    private rand: any = [];
    constructor(props: ChangeActivityRoomViewControl) {
        super(props);
        this.state = {
            data_info: [],
            data_activity_device_list: [],
        };
    }
    componentDidMount() {
        if (this.props.match!.params.key) {
            // 活动室详情
            request(this, AppServiceUtility.activity_service.get_activity_room_list!({ id: this.props.match!.params.key }, 1, 1))
                .then((datas: any) => {
                    let list: any = datas.result && datas.result[0] && datas.result[0]['device_list'] ? datas.result[0]['device_list'] : [];
                    if (list.length > 0) {
                        list = list.map((item: any) => {
                            item['key'] = this.getUniqueDeviceKey();
                            return item;
                        });
                    }
                    this.setState({
                        data_info: datas.result && datas.result[0] ? datas.result[0] : [],
                        data_activity_device_list: list,
                    });
                });
        }
    }
    backList() {
        history.back();
    }
    handleSubmit = (e: any) => {
        e.preventDefault();
        const { form } = this.props;
        form!.validateFields((err: Error, values: any) => {
            if (!err) {
                let formValue = {};
                let device_list: any = [];
                for (let key in values) {
                    if (key.indexOf('___') !== -1) {
                        let keys = key.split('___');
                        if (!device_list[keys[0]]) {
                            device_list[keys[0]] = {};
                        }
                        device_list[keys[0]][keys[1]] = values[key];
                    } else if (key === 'open_date') {
                        formValue['begin_date'] = values[key][0];
                        formValue['end_date'] = values[key][1];
                    } else {
                        formValue[key] = values[key];
                    }
                }
                let newDeviceList: any = [];
                for (let i in device_list) {
                    if (device_list[i]) {
                        newDeviceList.push(device_list[i]);
                    }
                }
                formValue['device_list'] = newDeviceList;
                formValue['id'] = this.props.match!.params.key;
                request(this, AppServiceUtility.activity_service.update_activity_room!(formValue))
                    .then((datas: any) => {
                        if (datas === 'Success') {
                            message.info('保存成功');
                            this.props.history!.goBack();
                        }
                    })
                    .catch((error: any) => {
                        message.error(error);
                    });
            }
        });
    }
    getUniqueDeviceKey() {
        let uniqueKey = this.getDeviceKey();
        while (this.rand.indexOf(uniqueKey) > -1) {
            uniqueKey = this.getDeviceKey();
        }
        this.rand.push(uniqueKey);
        return uniqueKey;
    }
    getDeviceKey() {
        return new Date().getTime() + '' + Math.ceil(Math.random() * 10) + '';
    }
    addDevice() {
        let list = this.state.data_activity_device_list;
        if (!list) {
            list = [];
        }
        list.push({
            key: this.getUniqueDeviceKey(),
        });
        this.setState({
            data_activity_device_list: list
        });
    }
    delThis(index: number) {
        let list = this.state.data_activity_device_list;
        if (!list) {
            return;
        }
        list.splice(index, 1);
        this.setState({
            data_activity_device_list: list
        });
    }
    onRangePickerChange(e: any) {
        console.log(e);
    }
    onRangePickerOk(e: any) {
        console.log(e);
    }
    render() {
        const redeirect = isPermission(this.props.permission!);
        if (redeirect) {
            return redeirect;
        }
        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 5 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 16 },
            },
        };
        const { getFieldDecorator } = this.props.form!;
        let { data_info, data_activity_device_list } = this.state;

        // 如果服务产品不为空则生成
        let device_list;
        if (data_activity_device_list && data_activity_device_list!.length > 0) {
            device_list = data_activity_device_list!.map((value: any, index: number) => {
                return (
                    <Card key={value.key}>
                        <Row>
                            <Button type='primary' onClick={() => this.delThis(index)}>删除此设备</Button>
                        </Row>
                        <Row type="flex" justify="center">
                            <Col span={12}>
                                <Form.Item label='设备名称'>
                                    {getFieldDecorator(`${value.key}___device_name`, {
                                        initialValue: value['device_name'] ? value['device_name'] : '',
                                        rules: [{
                                            required: true,
                                            message: '请输入设备名称'
                                        }],
                                    })(
                                        <Input autoComplete='off' placeholder="请输入设备名称" />
                                    )}
                                </Form.Item>
                                <Form.Item label='设备数量'>
                                    {getFieldDecorator(`${value.key}___device_num`, {
                                        initialValue: value['device_num'] ? value['device_num'] : '',
                                        rules: [{
                                            required: true,
                                            validator: (_: any, value: any, cb: any) => checkMin0(_, value, cb, '设备数量')
                                        }],
                                    })(
                                        <Input autoComplete='off' placeholder="请输入设备数量" />
                                    )}
                                </Form.Item>
                                <Form.Item label='设备图片'>
                                    {getFieldDecorator(`${value.key}___device_pic`, {
                                        initialValue: value['device_pic'] ? value['device_pic'] : '',
                                    })(
                                        <FileUploadBtn list_type={"picture-card"} contents={"plus"} action={remote.upload_url} beforeUpload={beforeUpload} />
                                    )}
                                </Form.Item>
                                <Form.Item label='备注'>
                                    {getFieldDecorator(`${value.key}___remarks`, {
                                        initialValue: value['remarks'] ? value['remarks'] : '',
                                    })(
                                        <TextArea />
                                    )}
                                </Form.Item>
                            </Col>
                        </Row>
                    </Card >
                );
            });
        }
        return (
            <MainContent>
                <Form {...formItemLayout} onSubmit={this.handleSubmit}>
                    <MainCard title='活动室信息'>
                        <Row type="flex" justify="center">
                            <Col span={12}>
                                <Form.Item label='活动室名称'>
                                    {getFieldDecorator('activity_room_name', {
                                        initialValue: data_info['activity_room_name'] ? data_info['activity_room_name'] : '',
                                        rules: [{
                                            required: true,
                                            message: '请输入活动室名称'
                                        }],
                                    })(
                                        <Input autoComplete='off' placeholder="请输入活动室名称" />
                                    )}
                                </Form.Item>
                                <Form.Item label='活动室图片'>
                                    {getFieldDecorator('photo', {
                                        initialValue: data_info['photo'] ? data_info['photo'] : '',
                                    })(
                                        <FileUploadBtn list_type={"picture-card"} contents={"plus"} action={remote.upload_url} beforeUpload={beforeUpload} />
                                    )}
                                </Form.Item>
                                <Form.Item label='最大参与人数'>
                                    {getFieldDecorator('max_quantity', {
                                        initialValue: data_info['max_quantity'] ? data_info['max_quantity'] : '',
                                        rules: [{
                                            required: true,
                                            validator: (_: any, value: any, cb: any) => checkMin1(_, value, cb, '最大参与人数')
                                        }],
                                    })(
                                        <Input autoComplete='off' placeholder="请输入最大参与人数" />
                                    )}
                                </Form.Item>
                                <Form.Item label='开放时间'>
                                    {getFieldDecorator('open_date', {
                                        initialValue: data_info['begin_date'] && data_info['end_date'] ? [moment(data_info['begin_date'], 'YYYY/MM/DD HH::mm'), moment(data_info['end_date'], 'YYYY/MM/DD HH::mm')] : '',
                                        rules: [{
                                            required: true,
                                            message: '请输入开放时间'
                                        }],
                                    })(
                                        <RangePicker
                                            showTime={{ format: 'HH:mm' }}
                                            format="YYYY-MM-DD HH:mm"
                                            placeholder={['开始时间', '结束时间']}
                                            onChange={this.onRangePickerChange}
                                            onOk={this.onRangePickerOk}
                                        />
                                    )}
                                </Form.Item>
                                <Form.Item label='地址'>
                                    {getFieldDecorator('address', {
                                        initialValue: data_info['address'] ? data_info['address'] : '',
                                        rules: [{
                                            required: true,
                                            message: '请输入地址'
                                        }],
                                    })(
                                        <Input autoComplete='off' placeholder="请输入地址" />
                                    )}
                                </Form.Item>
                                <Form.Item label='备注'>
                                    {getFieldDecorator('remarks', {
                                        initialValue: data_info['remarks'] ? data_info['remarks'] : '',
                                    })(
                                        <TextArea />
                                    )}
                                </Form.Item>
                            </Col>
                        </Row>
                    </MainCard>
                    <MainCard title='设备列表'>
                        {device_list}
                        <Card bordered={false}>
                            <Button type='primary' onClick={() => this.addDevice()}>新增设备</Button>
                        </Card>
                    </MainCard>
                    <MainCard>
                        <Row type="flex" justify="center" className="ctrl-btns">
                            <Button htmlType='submit' type='primary'>保存</Button>
                            <Button type='ghost' name='返回' htmlType='button' onClick={this.backList}>返回</Button>
                        </Row>
                    </MainCard>
                </Form>
            </MainContent >
        );
    }
}

/**
 * 控件：活动室新增页面控件
 * @description 活动室新增页面控件
 * @author
 */
@addon('ChangeActivityRoomViewControl', '活动室新增页面控件', '活动室新增页面控件')
@reactControl(Form.create<any>()(ChangeActivityRoomView), true)
export class ChangeActivityRoomViewControl extends ReactViewControl {
    /** 视图权限 */
    public permission?: Permission;
}